package cn.iocoder.yudao.module.bpm.api.task;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.bpm.api.task.dto.BpmCommonCreateReqDTO;
import cn.iocoder.yudao.module.bpm.api.task.dto.BpmCommonCreateRespDTO;
import cn.iocoder.yudao.module.bpm.service.definition.BpmCommonService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

/**
 * bpm公共接口实现
 * @Author 王铁
 * @Description TODO
 * @Date 2024/1/12 16:17
 * @Version 1.0
 */
@RestController
@Validated
public class BpmCommonApiImpl implements BpmCommonApi {


    @Autowired
    private BpmCommonService bpmCommonService;

    /**
     * 创建流程
     * @throws Exception
     */
    @Override
    public CommonResult<BpmCommonCreateRespDTO> createFlow(@RequestBody BpmCommonCreateReqDTO vo)  {
        return success(bpmCommonService.createProcessInstance(vo.getId(), vo.getKey(), vo.getVariables()));
    }

    /**
     * @param vo
     * @throws Exception
     */
    @Override
    public CommonResult<BpmCommonCreateRespDTO> createAndSubmitFlow(@RequestBody BpmCommonCreateReqDTO vo) {
        //判断是否存在提交处理人，如不存在就自己处理
        if (StringUtils.isBlank(vo.getAssignee())) {
            vo.setAssignee("" + SecurityFrameworkUtils.getLoginUserId());
        }
        //将处理人存入环境变量中
        vo.getVariables().put("assignee", vo.getAssignee());
        return success(bpmCommonService.createInstanceAndCompleteTask(vo.getId(), vo.getReason(), vo.getKey(), vo.getVariables()));
    }

    /**
     * @param vo
     * @throws Exception
     */
    @Override
    public CommonResult<BpmCommonCreateRespDTO> submitFlow(@RequestBody BpmCommonCreateReqDTO vo) {
        //判断是否存在提交处理人，如不存在就自己处理
        if (StringUtils.isBlank(vo.getAssignee())) {
            vo.setAssignee("" + SecurityFrameworkUtils.getLoginUserId());
        }
        //将处理人存入环境变量中
        vo.getVariables().put("assignee", vo.getAssignee());
        return success(bpmCommonService.completeTask(vo.getProcessInstanceId(), vo.getReason(), vo.getVariables()));
    }
}
